/****************************************************************************
 * Copyright (c) 2010 Torkild U. Resheim
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Torkild U. Resheim  - initial API and implementation
 *****************************************************************************/
package no.resheim.buildmonitor.ui.views.commands.log;

import no.resheim.buildmonitor.core.data.Job;
import no.resheim.buildmonitor.ui.log.LogInput;
import no.resheim.buildmonitor.ui.views.commands.AbstractCommandHandler;

import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.IStorage;
import org.eclipse.ui.IStorageEditorInput;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;

/**
 * Command handler for deleting a server instance from the system.
 * 
 * @author Torkild Ulvøy Resheim
 * @since 1.0
 */
public class OpenInEditor extends AbstractCommandHandler {

	private static final String LOG_EDITOR_ID = "org.eclipse.ui.DefaultTextEditor";

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		Object obj = getSelection(event);
		if (obj != null && obj instanceof Job) {
			IStorage log = ((Job) obj).getLog();
			IWorkbenchWindow window = PlatformUI.getWorkbench()
					.getActiveWorkbenchWindow();
			if (window != null && log != null) {
				IWorkbenchPage page = window.getActivePage();
				if (page != null) {
					IStorageEditorInput input = new LogInput(log);
					if (page != null)
						try {
							page.openEditor(input, LOG_EDITOR_ID);
						} catch (PartInitException e) {
							e.printStackTrace();
						}
				}
			}
		}
		return null;
	}
}
